import torch
# from modelscope import snapshot_download
# from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
# from qwen_vl_utils import process_vision_info
import transformers
import qwen_vl_utils
import os
import base64
import time

# from test.api_request import image_file
# default: Load the model on the available device(s)
# model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
# "Qwen/Qwen2.5-VL-7B-Instruct", torch_dtype="auto", device_map="auto"
# )
# 模型路径
model_dir = "/home/%s/models/qwen2.5_vl_7B" % os.getlogin()
# model_dir = "/home/%s/models/mlx-community/Qwen2.5-VL-3B-Instruct-3bit" % os.getlogin()
# model_dir = "/home/%s/models/Qwen/Qwen2-VL-2B-Instruct" % os.getlogin()


# 加载预训练模型
# model = transformers.Qwen2VLForConditionalGeneration.from_pretrained(
model = transformers.Qwen2_5_VLForConditionalGeneration.from_pretrained(
    model_dir,
    torch_dtype=torch.bfloat16,
    # torch_dtype="auto",
    device_map="auto"
)
#
processor = transformers.AutoProcessor.from_pretrained(model_dir, max_pixels=1280 * 28 * 28)

image_file_list = [
    "/home/%s/data/image/1997-SPCL-1-00073/00073-000001A.jpg" % os.getlogin(),
    "/home/%s/data/image/1997-SPCL-1-00073/00073-000002A.jpg" % os.getlogin(),
    "/home/%s/data/image/1997-SPCL-1-00073/00073-000003A.jpg" % os.getlogin()
]
first_result_list = [
    '入户材料审核意见表',
    '入户审批表',
    '入户申请表'
]
second_chat_list = [
    '这是一份入户材料审核意见表，请提取表中的姓名、性别、年龄、住址、承办人的审核内容、承办人、承办时间、处长意见、处长签字，按照json的格式输出',
    '这是一份入户材料审批意见表，请提取表中的京公户号、派出所名称、编号、户别、迁移原因、申请人姓名、申请入户地址、派出所承办人意见、所长意见、所长签名、所在签字时间、分局承办人意见、科长意见、科长签名、科长签字时间、分（县）局长意见、分（县）局长签名、分（县）局长签字时间、市局批示、市局批示人、市局批示时间，按照json的格式输出',
    '这是一份入户申请表，第一步请提取其中的分局名称、派出所名称、原户别、申请人姓名、性别、出生日期、结婚时间、文化程度、民族、身份证编码、现户口所在地、申请入户地址、入户理由、联系电话、填表日期。第二步请提取表中随迁人员的与申请入户人关系、姓名、性别、出生年月、身份证编码。第三步提取在京亲属与申请入户人关系、姓名、性别、出生年月、所在单位名称、户口所在地、何时来京、第四步提取外地亲属与申请入户人关系、姓名、出生年月、单位名称、户口所在地，最后按照json的格式输出。',
    '显示图片的标题和全部内容,按照json的中文格式输出'
]

# 推理
def chat_reason(image_base64, text0, processor, model):
    messages = [
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "image": "data:image/jpeg;base64," + image_base64,
                },
                {"type": "text", "text": text0},
            ],
        }
    ]
    # Preparation for inference
    text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    image_inputs, video_inputs = qwen_vl_utils.process_vision_info(messages)
    inputs = processor(
        text=[text],
        images=image_inputs,
        videos=video_inputs,
        padding=True,
        return_tensors="pt",
    )
    inputs = inputs.to(model.device)
    # inputs = inputs.to("cpu")

    # Inference: Generation of the output
    generated_ids = model.generate(**inputs, max_new_tokens=512)

    generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
    output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True,
                                         clean_up_tokenization_spaces=False)
    return output_text


for image_file in image_file_list:
    with open(image_file, 'rb') as f:
        image_base64 = base64.b64encode(f.read()).decode('utf-8')

    start_time = time.perf_counter()
    # first chat
    output_text = chat_reason(image_base64, "显示图片的标题,输出json中文格式", processor, model)

    proc_time = time.perf_counter() - start_time
    print(proc_time)

    resultJson = eval(output_text[0].lstrip('```json').rstrip('```'))
    title = resultJson['标题']
    print(title)
    index = -1
    for pos,fs in enumerate(first_result_list):
        if fs in title:
            index = pos
    if index < 0:
        index = len(first_result_list)
    # print('%d->%s'%(index,first_result_list[index]))
    second_text = second_chat_list[index]
    print(second_text)

    # second chat
    start_time = time.perf_counter()
    output_text = chat_reason(image_base64, second_text, processor, model)

    proc_time = time.perf_counter() - start_time
    print(proc_time)
    print(output_text)


'''
文本+base64编码
import base64
from PIL import Image
from io import BytesIO
from transformers import AutoProcessor, AutoModelForCausalLM

# 假设 processor 是你的模型对应的处理器类
processor = AutoProcessor.from_pretrained("model-name")

# 示例输入字典，包含文本和 Base64 编码的图像
input_dict = {
    "text": "这张图片展示了什么？",
    "image": "..."
}

# 解码 Base64 图像
image_data = base64.b64decode(input_dict["image"].split(",")[1])
image = Image.open(BytesIO(image_data))

# 预处理图像
image_inputs = processor(images=image, return_tensors="pt")

# 预处理文本
text_inputs = processor(input_dict["text"], return_tensors="pt")

# 应用聊天模板（假设 apply_chat_template 方法接受文本和图像输入）
# 注意：这里的 apply_chat_template 是假设的方法，具体实现可能不同
formatted_inputs = processor.apply_chat_template(text=text_inputs, images=image_inputs)

# 假设模型是用于生成文本的模型
model = AutoModelForCausalLM.from_pretrained("model-name")

# 生成文本
outputs = model(**formatted_inputs)
'''

'''
import base64
from PIL import Image
from io import BytesIO
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info

# 加载模型和处理器
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
    "Qwen/Qwen2.5-VL-7B-Instruct-AWQ", torch_dtype="auto", device_map="auto"
)
processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct-AWQ")

# 准备包含Base64编码图片的请求消息
messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
                "image": "...",
            },
            {"type": "text", "text": "Describe this image."},
        ],
    }
]

# 准备推理
text = processor.apply_chat_template(
    messages, tokenize=False, add_generation_prompt=True
)
image_inputs, video_inputs = process_vision_info(messages)
inputs = processor(
    text=[text],
    images=image_inputs,
    videos=video_inputs,
    padding=True,
    return_tensors="pt",
)
inputs = inputs.to("cuda")

# 推理：生成输出
generated_ids = model.generate(**inputs, max_new_tokens=128)
generated_ids_trimmed = [
    out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
]
output_text = processor.batch_decode(
    generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
print(output_text)
'''
